#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
封装百度OCR
注解
"""

__author__ = 'hubert'

import json
import requests

from aip import AipOcr
from aip import AipImageClassify

# 需注册百度AI账号，获取如下参数
APP_ID = '25698297'
API_KEY = 'YD0r5NXxFobtx1jpNASj7Pq2'
SECRET_KEY = 'mitxRr4ZyAuq8KEgolfbECjyWNSWsN3K'

# head
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 Edg/98.0.1108.55'
}


# """ 读取图片 """
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()


# 调用百度ocr能力
def baidu_ocr(img_path):
    # OCR客户端对象
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

    img = get_file_content(img_path)
    # 识别文字，图片为本地路径，返回json串，"workds" 为识别内容
    data = client.basicGeneral(img)
    return data


# 不用下载,用图片URL
def baidu_ocr_url(img_url):
    # OCR客户端对象，
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    data = client.basicGeneralUrl(img_url)
    return data


# 解析结果
def resolve_result(data):
    array_word = data.get("words_result")
    if array_word is not None:
        array_str = array_word[0]
        return array_str["words"]
    else:
        return ""


# 百度识别图片物体 https://cloud.baidu.com/doc/IMAGERECOGNITION/s/4k3bcxj1m
def baidu_image_classify(img_path):
    client = AipImageClassify(APP_ID, API_KEY, SECRET_KEY)

    image = get_file_content(img_path)

    """ 调用通用物体和场景识别 """
    result = client.advancedGeneral(image)
    return result


# 下载验证码图片
def dowload_captcha(img_url, img_name):
    r = requests.get(img_url, headers=headers, stream=True)
    if r.status_code == 200 :
        with open("/Users/hubert/Downloads/pic/"+img_name, "wb") as f_img:
            f_img.write(r.content)


# 测试
if __name__ == '__main__':
    r"""
    # {'words_result': [{'words': 'writing'}], 'words_result_num': 1, 'log_id': 1499324448891032389}
    # {'log_id': 1499325136097650558, 'error_msg': 'url format illegal', 'error_code': 282111}
    # result = baidu_ocr(path)
    # print(resolve_result(result))
    """
    path = "/Users/hubert/Downloads/pic/douban_captcha.jpeg"

    url = 'https://www.douban.com/misc/captcha?id=6cDHviFkm9bn3cDiRG5rf1Ai:en'
    img_name = '123.jpeg'
    dowload_captcha(url, img_name)

